﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;
using System.Text;

namespace LanguageInfo.Common.Utilities
{
	public class UrlHelper
	{
		/// <summary>
		/// 在url里添加参数，并返回添加后的url
		/// </summary>
		/// <param name="name"></param>
		/// <param name="value"></param>
		/// <returns></returns>
		public static string SetQueryString(string name, object value)
		{
			var query = HttpContext.Current.Request.Url.Query.TrimStart('?').Split('&');
			var newValue = name + '=' + value;

			bool isHase = false;
			if (query.Length > 0)
			{
				for (int i = 0; i < query.Length; i++)
				{
					isHase = (query[i].IndexOf('=') > -1) && (query[i].Substring(0, query[i].IndexOf('=')).Equals(name, StringComparison.OrdinalIgnoreCase));
				}
			}

			if (isHase)
			{
				return Regex.Replace(HttpContext.Current.Request.RawUrl,
					 name + "=" + "[^&#]*",
					 newValue, RegexOptions.IgnoreCase);
			}
			else
			{
				return HttpContext.Current.Request.RawUrl +
					 (HttpContext.Current.Request.RawUrl.IndexOf('?') > -1 ? '&' : '?') +
					 newValue;
			}

			//if (query.Any(i => i.IndexOf('=') > -1 && i.Substring(0, i.IndexOf('=')).Equals(name, StringComparison.OrdinalIgnoreCase)))
			//{
			//    return Regex.Replace(HttpContext.Current.Request.RawUrl,
			//        name + "=" + "[^&#]*",
			//        newValue, RegexOptions.IgnoreCase);
			//}
			//else
			//{
			//    return HttpContext.Current.Request.RawUrl +
			//        (HttpContext.Current.Request.RawUrl.IndexOf('?') > -1 ? '&' : '?') +
			//        newValue;
			//}
		}


		/// <summary>
		/// 将文件名编码成浏览器下载时可识别的文件名
		/// </summary>
		/// <param name="name">原始文件名</param>
		/// <param name="agent">浏览器</param>
		/// <returns></returns>
		public static string EncodeDownloadFilename(string name, string agent)
		{
			agent = agent.ToUpper();

			/// IE
			if (agent.IndexOf("IE") > -1)
			{
				return ToHexString(name);
			}
			/// FIREFOX
			else if (agent.ToUpper().IndexOf("FIREFOX") > -1)
			{
				return string.Format("=?UTF-8?B?{0}?=", Convert.ToBase64String(Encoding.UTF8.GetBytes(name)));
			}
			else
			{
				return Uri.EscapeDataString(name);				
			}
		}


		/// <summary>
		/// 为字符串中的非英文字符编码
		/// </summary>
		/// <param name="s"></param>
		/// <returns></returns>
		public static string ToHexString(string s)
		{
			char[] chars = s.ToCharArray();
			StringBuilder builder = new StringBuilder();
			for (int index = 0; index < chars.Length; index++)
			{
				bool needToEncode = NeedToEncode(chars[index]);
				if (needToEncode)
				{
					string encodedString = ToHexString(chars[index]);
					builder.Append(encodedString);
				}
				else
				{
					builder.Append(chars[index]);
				}
			}
			return builder.ToString();
		}
		/// <summary>
		///指定 一个字符是否应该被编码
		/// </summary>
		/// <param name="chr"></param>
		/// <returns></returns>
		private static bool NeedToEncode(char chr)
		{
			string reservedChars = "$-_.+!*'(),@=&";
			if (chr > 127)
				return true;
			if (char.IsLetterOrDigit(chr) || reservedChars.IndexOf(chr) >= 0)
				return false;
			return true;
		}
		/// <summary>
		/// 为非英文字符串编码
		/// </summary>
		/// <param name="chr"></param>
		/// <returns></returns>
		private static string ToHexString(char chr)
		{
			UTF8Encoding utf8 = new UTF8Encoding();
			byte[] encodedBytes = utf8.GetBytes(chr.ToString());
			StringBuilder builder = new StringBuilder();
			for (int index = 0; index < encodedBytes.Length; index++)
			{
				builder.AppendFormat("%{0}", Convert.ToString(encodedBytes[index], 16));
			}
			return builder.ToString();
		}
	}
}
